package com.bawei.mdm2207alast.mine.user

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.bawei.mdm2207alast.base.OnError
import com.bawei.mdm2207alast.base.OnLoading
import com.bawei.mdm2207alast.base.OnSuccess
import com.bawei.mdm2207alast.common.BaseTitle
import com.bawei.mdm2207alast.model.db.UserEntity
import com.bawei.mdm2207alast.route.RouteConfig
import com.blankj.utilcode.util.ToastUtils
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * 作者：赵亮
 * 时间：2024/12/23 14:13
 * 功能：登录页面
 */
@Composable
fun LoginPage(
    navController: NavController = rememberNavController(),
    viewModel: UserViewModel = hiltViewModel()
) {

    // 用户名
    var name by remember {
        mutableStateOf("")
    }

    // 密码
    var pass by remember {
        mutableStateOf("")
    }

    // 角色，默认选中经理
    var role by remember {
        mutableStateOf(2)
    }

    LaunchedEffect(key1 = "") {
        launch {
            viewModel.uiState.collect {
                when(it) {
                    is OnError -> {
                        ToastUtils.showShort("登录失败，用户名或密码错误")
                    }
                    OnLoading -> {}
                    is OnSuccess<*> -> {
                        ToastUtils.showShort("登录成功！")
                        val mmkv = MMKV.defaultMMKV()
                        mmkv.encode("username", name)
                        mmkv.encode("role", role)
                        mmkv.encode("uid", (it.data as UserEntity).uid)
                        navController.popBackStack()
                    }
                }
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
    ) {
        // 标题
        BaseTitle(navController = navController, title = "登录")
        Spacer(modifier = Modifier.height(10.dp))
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(horizontal = 15.dp),
            verticalArrangement = Arrangement.spacedBy(15.dp)
        ) {
            // 用户名输入框
            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),
                label = { Text(text = "用户名") },
                value = name,
                onValueChange = { name = it }
            )

            // 密码输入框
            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),
                label = { Text(text = "密码") },
                visualTransformation = PasswordVisualTransformation(),
                value = pass,
                onValueChange = { pass = it }
            )

            // 角色选择
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(text = "角色：")
                Checkbox(checked = role == 1, onCheckedChange = {
                    if (it) {
                        role = 1
                    }
                })
                Text(text = "员工")
                Checkbox(checked = role == 2, onCheckedChange = {
                    if (it) {
                        role = 2
                    }
                })
                Text(text = "经理")
            }

            // 登录按钮
            Button(modifier = Modifier.fillMaxWidth(), onClick = {
                if (name.isEmpty() || pass.isEmpty()) {
                    ToastUtils.showShort("请输入内容！")
                    return@Button
                }
                if (!name.matches(Regex("[0-9A-z_]{3,8}"))) {
                    ToastUtils.showShort("用户名不符合规范")
                    return@Button
                }
                viewModel.sendIntent(UserIntent.LoginIntent(name, pass, role))
            }) {
                Text(text = "登录")
            }

            Text(text = "去注册", color = Color.Blue, modifier = Modifier.clickable {
                // 跳转到注册页面
                navController.navigate(RouteConfig.REGISTER)
            })
        }

    }
}

@Preview
@Composable
fun LoginPagePreview() {
    LoginPage()
}

